extends TextureButton

var is_dragging = false
var first_location:Vector2 = Vector2.ZERO
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var SPEED = 300.0
var jump_speed = -400

var jump_position = false
var X_location:bool = false
var Y_location:bool = false#判断是否到达指定地点

var top_wall:bool = false##判断是否碰到墙壁
var bottom_wall:bool = false
var left_wall:bool = false
var right_wall:bool = false


func _ready():
	first_location = $"..".global_position
	set_process_input(true)

func _gui_input(event):
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if event.pressed :
				is_dragging = true
				$"..".modulate = Color(2, 2, 2, 1)
				grab_focus()  # 抓取焦点，以防止其他控件捕获鼠标事件
		else:
			if is_dragging:
				is_dragging = false
				$"..".modulate = Color(1, 1, 1, 1)
				release_focus()
				# 处理放下逻辑，这里可以执行您需要的操作

func _process(delta):
	move()
	

func _physics_process(delta):
	if !X_location || !Y_location: 
		pass

func move(): ##包括鼠标点击的移动与被动的移动
	$"..".velocity.x = 0
	$"..".velocity.y = 0
	if is_dragging:
		var global_mouse_pos = get_global_mouse_position()
		var global_my_pos = $"..".global_position
		$"..".velocity.x = (global_mouse_pos.x - global_my_pos.x)*10
		$"..".velocity.y = (global_mouse_pos.y - global_my_pos.y)*10
		$"..".move_and_slide()
	else:
		var x = 0
		var y = 0#判断有没有碰到墙
		
		var arr:Array
		if($"../碰撞" != null):
			arr = $"../碰撞".get_overlapping_areas()
		for i in arr:
			if !i.is_in_group("card"):
				if i.name == "WallTop":
					top_wall = true
				if i.name == "WallBottom":
					bottom_wall = true
				if i.name == "WallLeft":
					left_wall = true
				if i.name == "WallRight":
					right_wall = true
				continue
			var you = i.get_parent().global_position
			var me = $"..".global_position
			if abs(you.x-me.x) > abs(you.y-me.y):
				if you.x < me.x:
					$"..".velocity.x = 400
				else:
					$"..".velocity.x = -400
			else:
				if you.y < me.y:
					$"..".velocity.y = 400
				else:
					$"..".velocity.y = -400
		if($"..".velocity.x > 0 && right_wall):
			$"..".scale.x-=0.001
		elif($"..".velocity.x < 0 && left_wall):
			$"..".scale.x-=0.001
		elif($"..".velocity.y < 0 && top_wall):
			$"..".scale.y-=0.001
		elif($"..".velocity.y > 0 && bottom_wall):
			$"..".scale.y-=0.001
		else:
			$"..".scale.x=1
			$"..".scale.y=1
		right_wall = false
		left_wall = false
		top_wall = false
		bottom_wall = false
		$"..".move_and_slide()
		if($"..".scale.x < 0.4 || $"..".scale.y < 0.4):
			for i in arr:
				if i.is_in_group("card"):
					print(11)
					if(i.get_parent().name == "上顶" && $"..".name == "下底" || i.get_parent().name == "下底" && $"..".name == "上顶"):
						var sce = preload("res://场景/制造台/自动处理台.tscn").instantiate()
						sce.global_position = $"..".global_position
						$"..".get_parent().add_child(sce)
						
						print(11)
						i.get_parent().queue_free()
						$"..".queue_free()
						
						

##################################################
